import { cloneDeep } from 'lodash-es'
import { http } from '@/utils/http'
import { ElMessage, ElMessageBox } from 'element-plus'

import _ from 'lodash-es'

export const useSchemeStore = () => {
    const userStore = useUserStore()
    const router = useRouter()
    const state = reactive({
        schemOption: {},
        schemOptions: {},
        openname: '保存自动方案',
        filterlist: [],
        activefilterType: {
            name: 'into',
            display: '0'
        },
        activeNames: [],
        schemeloading: false,
        bctypes: []
    })

    const getschemeoption = (filter_obj_code) => {
        http
            .get(`/scheme/get_scheme_option`)
            .then(res => {
                state.schemOption = res.data
                state.schemOption.filter_obj_code = filter_obj_code
                state.schemOption.bc_type = []
                getschemoptions()
            })
            .finally(() => {
                state.schemeloading = false
            })
    }

    const getschemedata = (code) => {
        http
            .get(`/scheme/scheme_data?scheme_code=${code}`)
            .then(res => {
                console.log(res.data);
                state.schemeloading = false
                state.schemOption = res.data.scheme_config_obj
                state.schemOptions = JSON.parse(JSON.stringify(res.data.scheme_config_obj))
                state.schemOption.bc_type = res.data.scheme_config_obj.bc_type
            })
            .finally(() => {
                state.schemeloading = false
            })
    }

    const getschemoptions = () => {
        let data = JSON.parse(JSON.stringify(state.schemOption))
        data.giveup.giveup_condition.forEach(item => {
            item.option_list[1] = JSON.parse(JSON.stringify(item.option_list[0]))
        });
        data.pass.pass_condition.forEach(item => {
            item.option_list[1] = JSON.parse(JSON.stringify(item.option_list[0]))
        });
        data.into.into_condition.forEach(item => {
            item.option_list[1] = JSON.parse(JSON.stringify(item.option_list[0]))
        });

        state.schemeloading = false
        state.schemOptions = data

    }



    const getfilterlist = () => {
        http
            .get(`/filter/filter_list?page=1&page_size=9999`)
            .then(res => {
                let a = []
                res.data.list.forEach(item => {
                    if (item.task_type != "board_copy_task") {
                        a.push(item)
                    }
                });
                state.filterlist = a
            })
            .finally(() => { })
    }

    const getcondition = () => {
        let a = state.schemOptions[state.activefilterType.name][`${state.activefilterType.name}_condition`]
        return a
    }

    const changeactiveNames = () => {
        if (state.activefilterType.display == '0') {
            state.activeNames = []
        }
        if (state.activefilterType.display == '1') {
            state.activeNames = []
            let a = []
            state.schemOptions[state.activefilterType.name].forEach(item => {
                a.push(item.name)
            });
            state.activeNames = a

        }
    }

    const clicksave = () => {
        if (state.schemOptions.scheme_name == '') {
            ElMessage.error('请输入方案名称')
            return
        }
        if (state.schemOptions.filter_obj_code == '') {
            ElMessage.error('请选择过滤器')
            return
        }

        if (state.schemOptions.scheme_code == '' || state.schemOptions.scheme_code == null) {
            delete state.schemOptions.scheme_code
        }

        http.post('/scheme/creat_or_update_scheme', state.schemOptions).then(res => {
            console.log(res);
            if (res.code == 200) {
                // state.showfilterName = false
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                state.schemeloading = true
                router.replace(`fangan`)
                // setTimeout(() => {
                //     getschemoptions()
                // }, 1000);

            } else {
                ElMessage.error(res.msg)
            }

        }).finally(() => {
        })

    }

    const analyuls = () => {
        return new Promise((resolve, reject) => {
            const hash = window.location.hash // 获取哈希部分
            const queryString = hash.split('?')[1] || '' // 获取查询字符串部分
            const params = new URLSearchParams(queryString) // 解析查询字符串
            const scheme_code = params.get('scheme_code') // 获取特定参数
            const filter_obj_code = params.get('filter_obj_code') // 获取特定参数
            let a = {
                scheme_code: scheme_code,
                filter_obj_code: filter_obj_code
            }
            resolve(a)
        })
    }

    onMounted(async () => {
        initData()
    })

    onUnmounted(() => {
    })


    async function initData() {
        state.schemeloading = true
        // clear()

        getfilterlist()

        analyuls().then(code => {
            if (code.scheme_code != '' && code.scheme_code != null) {
                state.openname = '修改自动方案'
                getschemedata(code.scheme_code)
            } else {
                let a = ''
                state.openname = '保存自动方案'
                if (code.filter_obj_code != '' && code.filter_obj_code != null) {
                    a = code.filter_obj_code
                }
                getschemeoption(a)

            }
        })
        state.bctypes = userStore.user.subscribe[`${userStore.user.plant_code}:data_api`].selected.map(item => {
            return { value: item.value, label: item.name }
        })

        // http.get('/config/get_bc_type', { params: { page: 1, page_size: 999 } }).then(res => {
        //     state.bctypes = res.data.out_platform.map(item => {
        //       return { value: item.bc_type, label: item.name }
        //     })
        //     console.log(state.bctypes);

        //   })



    }


    return {
        state,

        getcondition,
        changeactiveNames,
        getschemoptions,
        clicksave

    }
}
